package org.dfzt.modules.system.util;

import cn.hutool.core.util.StrUtil;

import java.util.Random;

/**
 * @Description:
 * @author: cuiyf
 * @Date: 2020/6/28 18:11
 * @Version: 1.0
 */
public class RandomCodeUtil {
    private static final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";

    public static String randomCode(){
        //字母
        String letter = BASE_CHECK_CODES.substring(0,BASE_CHECK_CODES.length()-10);
        //数字
        String number = BASE_CHECK_CODES.substring(letter.length());
        int num = 0;
        int cc = 0;
        if (StrUtil.isEmpty(BASE_CHECK_CODES)) {
            return "";
        } else {
            StringBuilder sb = new StringBuilder(4);
            Random random = new Random();
            for(int i = 0; i < 4; ++i) {
                int n = random.nextInt(BASE_CHECK_CODES.length());
                char c = BASE_CHECK_CODES.charAt(n);
                //判断是否是数字字符
                if (Character.isDigit(c)){
                    num++;
                } else {
                    cc++;
                }
                if (num>3){
                    n = random.nextInt(letter.length());
                    sb.append(letter.charAt(n));
                } else if (cc>3){
                    n = random.nextInt(number.length());
                    sb.append(number.charAt(n));
                } else {
                    sb.append(BASE_CHECK_CODES.charAt(n));
                }
            }
            return sb.toString();
        }
    }
}
